package com.club.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.club.common.constant.Constant;
import com.club.common.constant.JwtConstant;
import com.club.entity.R;
import com.club.entity.SysUser;
import com.club.entity.SysUserRole;
import com.club.service.SysRoleService;
import com.club.service.SysUserRoleService;
import com.club.service.SysUserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.Date;

/**
 * @author zhangfc
 * @date 2022/11/8 13:12
 */
@Api(tags = "注册Controller")
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class RegisterController {

    private final SysUserService sysUserService;

    private final SysUserRoleService sysUserRoleService;

    /**
     * 注册
     *
     * @return R
     */
    @PostMapping("/register")
    public R register(@RequestBody SysUser sysUser) {
        String prePassword = sysUser.getPassword();
        String afterPassword = DigestUtil.md5Hex(JwtConstant.MD5_KEY + prePassword, Charset.defaultCharset());
        sysUser.setPassword(afterPassword);
        sysUser.setCreateTime(new Date());
        sysUser.setStatus(Constant.CloseStatus.NORMAL);
        sysUserService.save(sysUser);
        SysUserRole sysUserRole = SysUserRole.builder()
                .userId(sysUser.getId())
                .roleId(Constant.RoleConstant.GENERAL)
                .build();
        sysUserRoleService.save(sysUserRole);
        return R.ok();
    }
}
